package vn.bus.bk;

import java.util.ArrayList;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;

import vn.bus.bk.object.BusInfo;
import vn.bus.bk.other.Convert;
import vn.bus.bk.adapter.ListBusAdapter;
import vn.bus.bk.adapter.SQLiteAdapter;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

public class SearchByNumber extends SherlockFragmentActivity {

    private ListView myListViewBus;
    private ListBusAdapter myAdapter;
    private SQLiteAdapter mySQLAdapter;
    private Cursor mCursor;
    private int iNumber, iGoBus, iBackBus, iName, iTimeStartBus, iTimeEndBus,
	    iFrequency, iValue, iOrdinateGo, iOrdinateBack;
    private String[] columns;

    private ArrayList<BusInfo> myListBus, myListBusFromDB;
    private EditText textFilter;
    private ImageView searchFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.searchbynumber);
	myListBus = new ArrayList<BusInfo>();

	setTitle(getString(R.string.menu_item_1));
	columns = getResources().getStringArray(R.array.arrayColumn);
	getWindow().setSoftInputMode(
		WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
	getSupportActionBar().setDisplayHomeAsUpEnabled(true);
	getSupportActionBar().setHomeButtonEnabled(true);
	// Log.i("POSITION LIST", String.valueOf(positionList));
	init();
//	loadListFromDatabase();
//	setup();
	new LoadData().execute();
    }

    private void init() {
	// TODO Auto-generated method stub
	myListViewBus = (ListView) findViewById(R.id.listBus);
	searchFilter = (ImageView) findViewById(R.id.bt_search_filter);
	textFilter = (EditText) findViewById(R.id.et_search_filter);

	myListViewBus.setFastScrollEnabled(true);

    }

    private void loadListFromDatabase() {
	myListBusFromDB = new ArrayList<BusInfo>();

	mySQLAdapter = new SQLiteAdapter(this);
	try {
	    mySQLAdapter.close();
	    mySQLAdapter.copyDataBase();
	    // mySQLAdapter.decrypt();
	    mySQLAdapter.openDataBase();

	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    Log.i("DATABASE", "Cannot connect to database");
	}
	try {

	    mCursor = mySQLAdapter.rawAll();
	    mCursor.moveToFirst();
	    initialzeIndex();

	    do {
		myListBusFromDB.add(new BusInfo(mCursor.getInt(iNumber),
			mCursor.getString(iName), mCursor.getString(iGoBus),
			mCursor.getString(iBackBus), mCursor
				.getString(iTimeStartBus), mCursor
				.getString(iTimeEndBus), mCursor
				.getString(iFrequency), mCursor
				.getString(iValue), mCursor
				.getString(iOrdinateGo), mCursor
				.getString(iOrdinateBack)));
		mCursor.moveToNext();
	    } while (!mCursor.isAfterLast());

	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	mySQLAdapter.close();
	myListBus = myListBusFromDB;
	Log.i("SIZE ALL FROM DB", String.valueOf(myListBus.size()));
    }

    private void initialzeIndex() {
	// TODO Auto-generated method stub
	iNumber = mCursor.getColumnIndex(columns[0]);
	iGoBus = mCursor.getColumnIndex(columns[1]);
	iBackBus = mCursor.getColumnIndex(columns[2]);
	iName = mCursor.getColumnIndex(columns[3]);
	iTimeStartBus = mCursor.getColumnIndex(columns[4]);
	iTimeEndBus = mCursor.getColumnIndex(columns[5]);
	iFrequency = mCursor.getColumnIndex(columns[6]);
	iValue = mCursor.getColumnIndex(columns[7]);
	iOrdinateGo = mCursor.getColumnIndex(columns[8]);
	iOrdinateBack = mCursor.getColumnIndex(columns[9]);
    }

    private void setup() {
	// Adapter for ListView
	// for (int i = 0; i < 10 && i < myListBus.size(); i++) {
	// myPartListBus.add(myListBus.get(i));
	// }
	myAdapter = new ListBusAdapter(this, myListBus);

	myListViewBus.setAdapter(myAdapter);

	searchFilter.setOnClickListener(new View.OnClickListener() {

	    public void onClick(View arg0) {
		// TODO Auto-generated method stub
		filter();
	    }
	});

    }

    private void filter() {

	InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

	myListBus = new ArrayList<BusInfo>();
	// myAdapter.clear();

	String name = textFilter.getText().toString();
	name = name.toLowerCase();
	name = Convert.convert(name);
	name = name.trim();
	if (name.length() != 0) {
	    for (int i = 0; i < myListBusFromDB.size(); i++) {
		String nameBus = Convert.convertRoute(myListBusFromDB.get(i)
			.getName().toLowerCase().trim());
		if (Convert.check(name, nameBus)) {
		    myListBus.add(myListBusFromDB.get(i));
		}
	    }

	} else {
	    myListBus = myListBusFromDB;
	}
	myAdapter = new ListBusAdapter(SearchByNumber.this, myListBus);
	myListViewBus.setAdapter(myAdapter);

	imm.hideSoftInputFromWindow(textFilter.getWindowToken(), 0);
	Log.i("SIZE ALL", String.valueOf(myListBus.size()));

    }

    @Override
    protected void onResume() {
	// TODO Auto-generated method stub
	super.onResume();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	// TODO Auto-generated method stub
	if (item.getItemId() == android.R.id.home) {
	    finish();
	}
	return super.onOptionsItemSelected(item);
    }
    
    class LoadData extends AsyncTask<Void, Void, Void>{

	private ProgressDialog dialog;
	
	
	@Override
	protected void onPreExecute() {
	    // TODO Auto-generated method stub
	    super.onPreExecute();
	    dialog = new ProgressDialog(SearchByNumber.this);
	    dialog.setMessage("Đang tải dữ liệu");
	    dialog.show();
	}


	@Override
	protected void onPostExecute(Void result) {
	    // TODO Auto-generated method stub
	    super.onPostExecute(result);
	    dialog.dismiss();
	    setup();
	}


	@Override
	protected Void doInBackground(Void... params) {
	    // TODO Auto-generated method stub
	    loadListFromDatabase();
	    return null;
	}
	
    }
}
